package org.karelun.rabbit.rcp.policy;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.emf.common.command.Command;
import org.eclipse.emf.common.command.CompoundCommand;
import org.eclipse.emf.edit.command.CommandParameter;
import org.eclipse.emf.edit.command.CreateChildCommand;
import org.eclipse.emf.edit.command.SetCommand;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.karelun.ideaboard.gef.EditPart;
import org.karelun.ideaboard.gef.editpolicies.XYLayoutEditPolicy;
import org.karelun.ideaboard.gef.requests.ChangeBoundsRequest;
import org.karelun.ideaboard.gef.requests.CreateRequest;
import org.karelun.rabbit.graph.Diagram;
import org.karelun.rabbit.graph.GraphPackage;
import org.karelun.rabbit.graph.Shape;
import org.karelun.rabbit.rcp.editpart.ShapeEditPart;

public class DiagramLayoutEditPolicy extends XYLayoutEditPolicy{

	@Override
	protected Command getCreateCommand(CreateRequest request) {
		Object newObject = request.getNewObject();
		if(newObject==null){
			return null;
		}
		Diagram diagram=(Diagram)getHost().getModel();
		Shape shape=(Shape)newObject;
		Rectangle constraint=(Rectangle)getConstraintFor(request);
		shape.setX(constraint.x);
		shape.setY(constraint.y);
		shape.setHeight(50);
		shape.setWidth(50);
		EditingDomain editingDomain = (EditingDomain)getHost().getAdapter(EditingDomain.class);
		List<Object> collection=new ArrayList<Object>();
		collection.add(diagram);
		return CreateChildCommand.create(editingDomain, diagram, new CommandParameter(null, GraphPackage.Literals.DIAGRAM__SHAPES, shape),collection);
	}

	@Override
	protected Command createChangeConstraintCommand(
			ChangeBoundsRequest request, EditPart child, Object constraint) {
		if (!(child instanceof ShapeEditPart))
            return null;
        if (!(constraint instanceof Rectangle))
            return null;
        Shape shape=(Shape)child.getModel();
        Rectangle bound=(Rectangle)constraint;
        EditingDomain editingDomain = (EditingDomain)getHost().getAdapter(EditingDomain.class);
        
        CompoundCommand ret = new CompoundCommand();
        Command xcommand = SetCommand.create(editingDomain, shape, GraphPackage.Literals.RECTANGLED__X, new Integer(bound.x));
        Command ycommand = SetCommand.create(editingDomain, shape, GraphPackage.Literals.RECTANGLED__Y, new Integer(bound.y));
        Command wcommand = SetCommand.create(editingDomain, shape, GraphPackage.Literals.RECTANGLED__WIDTH, new Integer(bound.width));
        Command hcommand = SetCommand.create(editingDomain, shape, GraphPackage.Literals.RECTANGLED__HEIGHT, new Integer(bound.height));
        ret.append(xcommand);
        ret.append(ycommand);
        ret.append(wcommand);
        ret.append(hcommand);
         return ret;
	}
}